找传奇、传世资源到传世资源站!

TCP简单文件传输源码(含发送端以及接收端)

8.5玩家评分(1人评分)
下载后可评
介绍 评论 失效链接反馈

from clipboard
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Net;using System.Net.Sockets;using System.IO;namespace 使用Tcp协议传输文件{ public partial class 发送端 : Form { private TcpClient tcpclient; private FileStream fs; private NetworkStream ns; public 发送端() { InitializeComponent(); } private void btn_Select_Click(object sender, EventArgs e) { OpenFileDialog ofdialog = new OpenFileDialog(); if(ofdialog.ShowDialog()==DialogResult.OK) { label1.Text = ofdialog.FileName; } } private void btn_Send_Click(object sender, EventArgs e) { if(txtBox_IPAddress.Text.Equals("")) { MessageBox.Show("输入IP地址"); return; } if(label1.Text.Equals("文件路径:")) { MessageBox.Show("请选择一个文件"); return; } tcpclient =new TcpClient(); tcpclient.BeginConnect(IPAddress.Parse(txtBox_IPAddress.Text), 8080, new AsyncCallback((IAsyncResult Iar) => { this.tcpclient = (TcpClient)Iar.AsyncState; this.tcpclient.EndConnect(Iar); if (this.tcpclient.Connected) { MessageBox.Show("连接成功,现在开始传输"); try { using (ns = this.tcpclient.GetStream()) { fs = new FileStream(label1.Text, FileMode.Open); byte[] buffer = new byte[1024]; fs.Read(buffer, 0, buffer.Length); int len = fs.Read(buffer, 0, buffer.Length); while (len > 0) { ns.Write(buffer, 0, len); len = fs.Read(buffer, 0, buffer.Length); } fs.Close(); } tcpclient.Close();//关闭连接 ns = null; tcpclient = null;//初始化 } catch (Exception SEND_ERROR) { MessageBox.Show("遇到 " SEND_ERROR.Message "\n 传输失败 "); tcpclient.Close(); tcpclient = null;//初始化 } } }) , tcpclient); } }}

评论

发表评论必须先登陆, 您可以 登陆 或者 注册新账号 !


在线咨询: 问题反馈
客服QQ:174666394

有问题请留言,看到后及时答复